'use strict';

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

// Generated by CoffeeScript 2.2.3
// Import
var exec, extractOptsAndCallback, filterByInterface, getMac, isMac, getIp, isWindows, macRegex, zeroRegex;

var _require = require('child_process');

exec = _require.exec;

var isLoad = false,
    activeList = [],
    noActiveList = [],
    allList = [];
extractOptsAndCallback = require('extract-opts');

// Prepare
isWindows = process.platform.indexOf('win') === 0;

macRegex = /(?:[a-z0-9]{2}[:\-]){5}[a-z0-9]{2}/ig;

zeroRegex = /(?:[0]{2}[:\-]){5}[0]{2}/;

// Filter By Interface
// filterByInterface(iface, str)
filterByInterface = function filterByInterface(iface, str) {
    var i, len, line, lines, match, padding, result;
    iface = new RegExp(iface + '[:\\s]');
    lines = str.split(/\r?\n/g);
    result = '';
    padding = null;
    for (i = 0, len = lines.length; i < len; i++) {
        line = lines[i];
        if (result.length === 0) {
            if (iface.test(line)) {
                result += line;
            }
            continue;
        } else if (padding === null) {
            match = /^(\s+)/.exec(line);
            if (match) {
                result += '\n' + line;
                padding = new RegExp('^' + match[1]);
                continue;
            }
        } else {
            match = padding.exec(line);
            if (match) {
                result += '\n' + line;
                continue;
            }
        }
        break;
    }
    return result;
};
getIp = function getIp() {
    var interfaces = require('os').networkInterfaces();
    var ret = []
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (!devName.includes("VMware") && alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                ret.push(alias.address);
            }
        }
    }
    return ret;
}
// Get Mac
// next(err,macAddress)
getMac = function getMac(opts, next) {
    var command, data, extractMac, iface, isActive;
    // Prepare

    var _extractOptsAndCallba = extractOptsAndCallback(opts, next);

    var _extractOptsAndCallba2 = _slicedToArray(_extractOptsAndCallba, 2);

    opts = _extractOptsAndCallba2[0];
    next = _extractOptsAndCallba2[1];
    var _opts = opts;
    data = _opts.data;
    iface = _opts.iface;
    isActive = _opts.active;
    if (typeof isActive === "undefined") {
        isActive = "all";
    }
    if (data == null) {
        data = null;
    }
    if (iface == null) {
        iface = null;
    }
    // Command
    command = isWindows ? "chcp 65001&getmac" : "ifconfig -a || ip link";
    // Extract Mac
    extractMac = function extractMac(data, next) {
        var err, isZero, macAddress, match, result;
        if (iface) {
            // Prepare
            data = filterByInterface(iface, data);
        }
        result = [];
        // Find a valid mac address
        match = macRegex.exec(data)
        while (match) {
            let next = macRegex.exec(data)
            macAddress = match[0];
            let isOnline = !data.slice(match.index, next ? next.index : data.length).includes("disconnected");

            match = next;
            isZero = zeroRegex.test(macAddress);
            if (isZero === false) {
                if (isOnline) activeList.push(macAddress);
                else noActiveList.push(macAddress);
                allList.push(macAddress);
            }

        }
        if (isActive === "all") {
            result = allList;
        } else if (isActive) {
            result = activeList;
        } else {
            result = noActiveList;
        }
        // We have no mac address so return an error
        if (result === null) {
            err = new Error('could not determine the mac address from:\n' + data);
            return next(err);
        }
        // Forward with result
        return next(null, result);
    };
    // If we already have data go straight to extracting the mac
    if (!isLoad) {
        isLoad = true;
        if (data) {
            return extractMac(data, next);
        } else {
            // Otherwise fetch the data first
            return exec(command, function (err, stdout, stderr) {
                if (err) {
                    // Exit if error
                    return next(err);
                }
                // Otherwise forward
                return extractMac(stdout, next);
            });
        }
    } else {
        if (isActive === "all") {
            return process.nextTick(function () {
                next(null, allList)
            });
        } else if (isActive) {
            return process.nextTick(function () {
                next(null, activeList);
            });
        } else {
            return process.nextTick(function () {
                next(null, noActiveList);
            });
        }
    }
};

// Is Mac
isMac = function isMac(macAddress) {
    var ref;
    return ((ref = String(macAddress).match(macRegex)) != null ? ref.length : void 0) === 1;
};

// Export
module.exports = { macRegex: macRegex, getMac: getMac, isMac: isMac, getIp: getIp };